package com.lance.answer.gui.answer;

import com.alibaba.fastjson.JSONObject;
import com.lance.answer.util.Constant;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

// 2021-5-13
public class AdminBasicTest2AndAnswerNew {

   /* public static void main(String[] args) throws Exception {
        File file = new File("/Users/guiliangzhou/IdeaProjects/answerTool/src/main/resources/answer" + "/02326.json");
        String answerStr = FileUtils.readFileToString(file,"utf-8");
        List<AnswerObject> list = JSONObject.parseArray(answerStr,AnswerObject.class);
        Map<String,AnswerObject> map = new HashMap<>();
        for (AnswerObject answerObject:list) {
            map.put(answerObject.getQuestionCode(),answerObject);
        }
        run(map);
    }*/
    public static void start(String subjectCode,String userName,String password,String driverPath) throws Exception {
        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectCode + "/" + subjectCode +".answer");
        String answerStr = IOUtils.toString(inputStream);

/*
        File file = new File("/Users/guiliangzhou/IdeaProjects/answerTool/src/main/resources/" + subjectCode + "/" + subjectCode +".answer");
        String answerStr = FileUtils.readFileToString(file,"utf-8");
*/
        List<AnswerObject> list = JSONObject.parseArray(answerStr,AnswerObject.class);
        Map<String,AnswerObject> map = new HashMap<>();
        for (AnswerObject answerObject:list) {
            map.put(answerObject.getQuestionCode(),answerObject);
        }
        run(null,map,subjectCode,driverPath,userName,password);

    }


    // 管理学基础 2065001457555 19940419
    public static void run(List<String> urlTasks,Map<String,AnswerObject> answers,String subjectCode,String driverPath,String userName,String password) throws Exception {
        WebDriver driver = Util.getDriver(driverPath);
        //String url = "http://student.ouchn.cn/";
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        //Util.switchToFirst(driver);
        Thread.sleep(3000);
        // 形考作业的链接 管理学
        //List<String> urlTasks = Util.getCourseTaskUrl(driver, CourseTypeEnum.BasicManagement.name);
        //List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);

        //chromeDriver.navigate().refresh();
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.contains(Constant.SUBJECT.get(subjectCode))) {
                continue;
            }
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            //Util.switchToLast(driver);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

            System.out.println(urlTasks.toString());
        for (String urlTask : urlTasks) {
            // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
            driver.get(urlTask);
            Thread.sleep(2 * 1000);
            // 点击继续作业

            try {
                WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
                doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
            } catch (Exception e) {
                System.err.println("taskUrl:" + urlTask + "  occur error");
                e.printStackTrace();
            }
            Thread.sleep(2 * 1000);
           //回到试题首页
            WebElement element = driver.findElement(By.id("quiznavbutton1"));
            element.click();
            Thread.sleep(2 * 1000);
            // 回到首页
            //Util.goHomePageIndex(driver);
            boolean hashNextPage = true;
            while (hashNextPage) {
                try {
                    Thread.sleep(4000);
                    // 单个页面的所有题目的集合
                    List<WebElement> singlePageQuestion = Util.getSinglePageQuestionList(driver);
                    // 遍历每个问题|题目
                    for (WebElement singleSubject : singlePageQuestion) {

                        WebElement contentElement = singleSubject.findElement(By.className("content"));
                        // qtext 题目标题
                        WebElement qTitleElement = contentElement.findElement(By.className("qtext"));

                        // 题目名称
                        String title = qTitleElement.getText();
                        /*if (title.contains("\n")) {
                            title = title.split("\n")[0];
                        }
*/
                        // FIXME 接口传入qTitleElement和subjectId 来获取正确答案；
                        // FIXME 返回值是字符串或者集合
                        // ------HTTP获取

                        String questionCode = MD5Utils.encode(subjectCode + title);

                        if (!answers.containsKey(questionCode)) {


/*
                            File file = new File("/Users/guiliangzhou/IdeaProjects/answerTool/src/main/resources/answer/02326.error");
                            //FileUtils.writeLines(file, Lists.newArrayList(title,questionCode));
                            FileUtils.write(file,title + "\r\n" + questionCode + "\r\n",true);
*/


                            System.out.println("答案不存在");
                            System.out.println(title);
                            continue;
                        }

                        AnswerObject answerObject = answers.get(questionCode);
                        String realAnswer = "组织资源和组织目标";
                        // FIXME 返回的字段类型
                        int answerType = 1;
                        // FIXME 填空题没有answer
                        // ------HTTP获取

                        WebElement answerElement = Util.findByClassName(contentElement, "answer");
                        //处理答案乱码
//                        List<String> list = new ArrayList<>();
//                        for (String str:answerObject.getAnswers()) {
//                            str = new String(str.getBytes(),"utf-8");
//                            list.add(str);
//                        }

                        if (null != answerElement) {
                            // 开始答题
                            Util.doExercise(driver, answerElement, answerObject.getQuestionType(), answerObject.getAnswers());
                        }
                        //  FIXME 此时答案是没有保存的，要点击结束试答题
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Thread.sleep(2000);
                    // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                    WebElement nextPage = Util.findNextPage(driver);
                    if (nextPage != null) {
                        nextPage.click();
                    } else {
                        hashNextPage = false;
                        // FIXME  此时答案是没有保存的，要点击结束试答题 当没有下一页的时候，可以选择提交
                    }
                }
            }



            Thread.sleep(2000);

            //回到试题首页 (保存最后一题答案)
           /* WebElement element2 = driver.findElement(By.id("quiznavbutton1"));
            element2.click();*/

            WebElement submitbtns = driver.findElement(By.className("submitbtns"));
            WebElement next = submitbtns.findElement(By.cssSelector("input[name='next']"));
            next.click();
            Thread.sleep(2000);


//            //提交答案
//            List<WebElement> saveButtons = driver.findElements(By.cssSelector("button[type='submit']"));
//            System.out.println("提交");
//            System.out.println(saveButtons.size());
//            if (!CollectionUtils.isEmpty(saveButtons)) {
//                for (WebElement webElement:saveButtons) {
//                    String text = webElement.getText();
//                    if (text.contains("提交")) {
//                        webElement.click();
//                    }
//                }
//            }

            TimeUnit.SECONDS.sleep(3);
            //全部提交
            //提交答案

//            List<WebElement> confirmation = driver.findElements(By.className("confirmation-dialogue"));
//            System.out.println("确认弹框");
//            System.out.println(confirmation.size());
//            System.out.println(confirmation.toString());
//            if (!CollectionUtils.isEmpty(confirmation)) {
//                for (WebElement webElement:confirmation) {
//                    List<WebElement> submitElement = webElement.findElements(By.tagName("input"));
//                    System.out.println("再次确认按钮");
//                    System.out.println(submitElement.size());
//                    if (!CollectionUtils.isEmpty(submitElement)) {
//                        for (WebElement element1:submitElement) {
//                            String value = element1.getAttribute("value");
//                            System.out.println("不是空的");
//                            System.out.println(value);
//                            System.out.println("按钮长这样");
//                            System.out.println(element1.toString());
//                            if (value.contains("提交")) {
//                                //点击确认后页面会刷新,此时为了防止丢到元素抛异常，这里直接获取第一个，不再循环
//                                element1.click();
//                                break;
//                            }
//
//                        }
//                    }
//                }
//            }

/*
            List<WebElement> submitButtons = driver.findElements(By.tagName("input"));
            System.out.println("空的吗");
            System.out.println(submitButtons.toString());
            if (!CollectionUtils.isEmpty(submitButtons)) {
                for (WebElement webElement:submitButtons) {
                    String text = webElement.getText();
                    System.out.println("不是空的");
                    System.out.println(text);
                    if (text.contains("提交")) {
                        webElement.click();
                    }
                }
            }
*/

            TimeUnit.SECONDS.sleep(2);


        }

        Thread.sleep(5000);
        driver.close();
        driver.quit();
    }



}
